package com.realbrand.net.realbrandpay.ui.activity.shopcar;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.bean.LatBean;
import com.realbrand.net.realbrandpay.bean.LocationBean;

import com.realbrand.net.realbrandpay.inter.IGetWorkAddress;
import com.realbrand.net.realbrandpay.untils.HttpRequest;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/7/5.
 */

public class BaiduMapActivity extends BaseActivity {
    @BindView(R.id.baidu_mapView)
    MapView baiduMapView;

    BaiduMap map;
    String lat = "";
    String lng = "";
    //坐标点集合
    List<LatBean> list;
    List<OverlayOptions> optionses;
    List<LocationBean> address;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                   LatBean laybean= (LatBean) msg.getData().getSerializable("latBean");
                    L.d("获取的经纬度" + laybean.toString());
                    BitmapDescriptor bitmap = BitmapDescriptorFactory
                            .fromResource(R.drawable.location);
                    list.add(laybean);
                    //在地图上标记
                    for (int i = 0; i < list.size(); i++) {
                        MarkerOptions options = new MarkerOptions()
                                .position(list.get(i).getLatLng())
                                .icon(bitmap)
                                .zIndex(9);
                        optionses.add(options);
                        Marker marker = (Marker) map.addOverlay(options);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("bean", list.get(i));
                        marker.setExtraInfo(bundle);
                    }
//                    map.addOverlays(optionses);
                    //将每个点用线连接起来
                    if (list.size() > 1) {
                        List<LatLng> data=new ArrayList<>();
                        for (int i=0;i<list.size();i++){
                           data.add(list.get(i).getLatLng());
                        }
                        OverlayOptions overlayOptions = new PolylineOptions().width(10).color(0xAAFF0000).points(data);
                        Polyline polyline = (Polyline) map.addOverlay(overlayOptions);
                    }
                    //定义中心点
                    MapStatus mapStatus = new MapStatus.Builder().target(list.get(list.size() - 1).getLatLng()).zoom(10).build();
                    //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                    MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
                    //改变地图状态
                    map.setMapStatus(mapStatusUpdate);
                    map.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {
                            LatBean b = (LatBean) marker.getExtraInfo().getSerializable("bean");
                            Button button = new Button(BaiduMapActivity.this);
                            button.setText(b.getName() +"\n"+ b.getTime());
                            InfoWindow infoWindow = new InfoWindow(button, marker.getPosition(), -47);
                            map.showInfoWindow(infoWindow);
                            return false;
                        }
                    });

                    break;
                case 1:
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < address.size(); i++) {
                                    final String add = address.get(i).getAddress();
                                    final int finalI = i;
                                    getAddress(add, address.get(finalI).getReadTime(), address.get(finalI).getEnterpriseName());
                                }
                            }
                        }).start();

                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
//        baidiMapToolBar.setTitle("");
//        baidiMapToolBar.setNavigationIcon(R.mipmap.ic_back);
//        setSupportActionBar(baidiMapToolBar);
//        baidiMapToolBar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
        //获取商品码
        String scan = getIntent().getStringExtra("scan");
        //加载地图
        map = baiduMapView.getMap();
        list = new ArrayList<>();
        optionses = new ArrayList<>();
        //获取地址
        getScanAddress(scan);
        //获取经纬度
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                getAddress("安徽省安庆市");
//            }
//        }).start();
    }

    private void getScanAddress(String scan) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("SOURCE", "BaiduMapActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("METHOD", "GetWorkAddress");
            jsonObject.put("CommodityCode", scan);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            IGetWorkAddress iGetWorkAddress = HttpRequest.request_BASE_URL_VERSION(IGetWorkAddress.class, HTTPAPI.BASE_URL);
            iGetWorkAddress.getAddress(body).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String result = response.body().string();
                        L.d("获取地址返回结果" + result);
                        if ("".equals(result)) {
                            return;
                        } else {
                            JSONObject object = new JSONObject(result);
                            JSONArray workAddress = object.getJSONArray("WorkAddress");
                            JSONArray readTime = object.getJSONArray("ReadTime");
                            JSONArray enterpriseName = object.getJSONArray("EnterpriseName");
                            address = new ArrayList<LocationBean>();
                            for (int i = 0; i < workAddress.length(); i++) {

                                LocationBean bean = new LocationBean();
                                bean.setReadTime(readTime.getString(i));
                                bean.setAddress(workAddress.getString(i));
                                bean.setEnterpriseName(enterpriseName.getString(i));
                                address.add(bean);
                            }
                            Message obtain = Message.obtain();
                            obtain.what = 1;
                            handler.sendMessage(obtain);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.act_baidu_map;
    }

    @Override
    protected void setOnClick() {

    }

    @Override
    public void onClick(View v) {

    }

    public void getAddress(String add, String readTime, String address) {
        String addr = "";

        try {
            addr = java.net.URLEncoder.encode(add, "UTF-8");//编码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = String.format("http://api.map.baidu.com/geocoder/v2/?address=%s&ak=K1Fv76hhixzgMznlLn0neshV3oYl94e7&output=json&callback=showLocation&mcode=7A:52:BA:2B:73:7C:29:84:0A:FF:C3:43:0F:2D:08:27:DE:C1:21:15;com.realbrand.net.realbrandpay", addr);
        URL myURL = null;
        URLConnection httpsConn = null;
        //进行转码
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            httpsConn = (URLConnection) myURL.openConnection();//建立连接
            if (httpsConn != null) {
                InputStreamReader insr = new InputStreamReader(//传输数据
                        httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                String data = null;
                if ((data = br.readLine()) != null) {
                    System.out.println(data);
                    lat = data.substring(data.indexOf("\"lat\":") + ("\"lat\":").length(), data.indexOf("},\"precise\""));
                    lng = data.substring(data.indexOf("\"lng\":") + ("\"lng\":").length(), data.indexOf(",\"lat\""));
                    Message obtain = Message.obtain();
                    obtain.what = 0;
//                    obtain.obj = data;
                    LatBean latBean=new LatBean();
                    latBean.setLat(lat);
                    latBean.setLng(lng);
                    latBean.setTime(readTime);
                    latBean.setName(address);
                    double v = Double.parseDouble(lat);
                    double v1 = Double.parseDouble(lng);
                    LatLng latLng = new LatLng(v, v1);
                    latBean.setLatLng(latLng);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("latBean",latBean);
                    obtain.setData(bundle);
                    handler.sendMessage(obtain);
                    //这里的data为以下的json格式字符串,因为简单，所以就不使用json解析了，直接字符串处理
                    //{"status":0,"result":{"location":{"lng":118.77807440802562,"lat":32.05723550180587},"precise":0,"confidence":12,"level":"城市"}}
                    L.d("获取的经纬度" + data.toString());

                }
                insr.close();
                br.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
